import argparse
import os
import sys
from CryptoFarm.db import LocalDB_JSON
from CryptoFarm.utils import create_session


def cancel(resp):
    if resp == 'q' or resp == 'exit' or resp == '!q':
        sys.exit(0)


def main(args):
    if args.new:
        create_new_user()
    elif args.create_sessions:
        create_session()
    else:
        djb = LocalDB_JSON()
        users = djb.get_users()
        for user in users:
            if not os.path.exists(f'{user['file_session']}.session'):
                print(f'Not found session for {user['file_session']}\nCheck for all users...')
                create_session()
                break


def create_new_user():
    djb = LocalDB_JSON()
    api_id = input(
        'Please entry your api_ID (Write q or press crl + C for exit)\n>> ')
    cancel(api_id)
    api_hash = input('Please entry your api_HASH\n>> ')
    cancel(api_hash)
    djb.create_user(api_id, api_hash)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description='This script help you manage this bot')
    parser.add_argument('-new', action='store_true',
                        help='If you wont create new user')
    parser.add_argument('--create-sessions', action='store_true',
                        help='Need for creating session files')
    main(parser.parse_args())
